<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="方案名称" prop="schemeName">
        <el-input
          v-model="queryParams.schemeName"
          placeholder="请输入方案名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="方案编码" prop="schemeCode">
        <el-input
          v-model="queryParams.schemeCode"
          placeholder="请输入方案编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职业名称" prop="professionName">
        <el-input
          v-model="queryParams.professionName"
          placeholder="请输入职业名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="评价方式" prop="evaluationMethod">
        <el-select
          v-model="queryParams.evaluationMethod"
          placeholder="请选择评价方式"
          clearable
          class="!w-240px"
        >
          <el-option label="认定评价" value="assessment" />
          <el-option label="考试评价" value="examination" />
          <el-option label="混合评价" value="mixed" />
        </el-select>
      </el-form-item>
      <el-form-item label="方案状态" prop="schemeStatus">
        <el-select
          v-model="queryParams.schemeStatus"
          placeholder="请选择方案状态"
          clearable
          class="!w-240px"
        >
          <el-option label="草稿" :value="0" />
          <el-option label="已发布" :value="1" />
          <el-option label="已停用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:scheme:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:scheme:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 统计卡片 -->
  <el-row :gutter="20" class="mb-4">
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-blue-600">{{ statistics.totalCount || 0 }}</div>
            <div class="text-gray-500">总方案数</div>
          </div>
          <Icon icon="ep:document-copy" class="text-4xl text-blue-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-green-600">{{ statistics.publishedCount || 0 }}</div>
            <div class="text-gray-500">已发布</div>
          </div>
          <Icon icon="ep:check" class="text-4xl text-green-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-orange-600">{{ statistics.draftCount || 0 }}</div>
            <div class="text-gray-500">草稿</div>
          </div>
          <Icon icon="ep:edit" class="text-4xl text-orange-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-purple-600">{{ statistics.defaultCount || 0 }}</div>
            <div class="text-gray-500">默认方案</div>
          </div>
          <Icon icon="ep:star" class="text-4xl text-purple-600" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="方案编码" align="center" prop="schemeCode" width="120" />
      <el-table-column label="方案名称" align="center" prop="schemeName" width="200" />
      <el-table-column label="职业名称" align="center" prop="professionName" width="150" />
      <el-table-column label="适用等级" align="center" prop="applicableLevels" width="120" />
      <el-table-column label="评价方式" align="center" prop="evaluationMethod" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.EVAL_EVALUATION_METHOD" :value="scope.row.evaluationMethod" />
        </template>
      </el-table-column>
      <el-table-column label="方案版本" align="center" prop="schemeVersion" width="100" />
      <el-table-column label="方案状态" align="center" prop="schemeStatus" width="100">
        <template #default="scope">
          <el-tag :type="getSchemeStatusTagType(scope.row.schemeStatus)">
            {{ getSchemeStatusText(scope.row.schemeStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="默认方案" align="center" prop="isDefault" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isDefault ? 'success' : 'info'">
            {{ scope.row.isDefault ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:scheme:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:scheme:update']"
            v-if="scope.row.schemeStatus === 0"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="publish" v-if="scope.row.schemeStatus === 0">
                  发布
                </el-dropdown-item>
                <el-dropdown-item command="disable" v-if="scope.row.schemeStatus === 1">
                  停用
                </el-dropdown-item>
                <el-dropdown-item command="setDefault" v-if="!scope.row.isDefault && scope.row.schemeStatus === 1">
                  设为默认
                </el-dropdown-item>
                <el-dropdown-item command="copy">
                  复制
                </el-dropdown-item>
                <el-dropdown-item command="template">
                  模板配置
                </el-dropdown-item>
                <el-dropdown-item command="delete" v-if="scope.row.schemeStatus !== 1">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SchemeForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <SchemeDetail ref="detailRef" />
  
  <!-- 复制弹窗 -->
  <SchemeCopy ref="copyRef" @success="getList" />
  
  <!-- 模板配置弹窗 -->
  <SchemeTemplateConfig ref="templateConfigRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalSchemeVO, 
  EvalSchemePageReqVO, 
  getSchemePage, 
  deleteScheme, 
  exportScheme,
  publishScheme,
  disableScheme,
  setDefaultScheme,
  copyScheme
} from '@/api/eval/scheme'
import SchemeForm from './SchemeForm.vue'
import SchemeDetail from './SchemeDetail.vue'
import SchemeCopy from './SchemeCopy.vue'
import SchemeTemplateConfig from './SchemeTemplateConfig.vue'

/** 评价方案 列表 */
defineOptions({ name: 'EvalScheme' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalSchemeVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statistics = ref<any>({}) // 统计数据
const queryParams = reactive<EvalSchemePageReqVO>({
  pageNo: 1,
  pageSize: 10,
  schemeName: undefined,
  schemeCode: undefined,
  professionName: undefined,
  evaluationMethod: undefined,
  schemeStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getSchemePage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 计算统计数据
    calculateStatistics()
  } finally {
    loading.value = false
  }
}

/** 计算统计数据 */
const calculateStatistics = () => {
  const totalCount = list.value.length
  const publishedCount = list.value.filter(item => item.schemeStatus === 1).length
  const draftCount = list.value.filter(item => item.schemeStatus === 0).length
  const defaultCount = list.value.filter(item => item.isDefault).length
  
  statistics.value = {
    totalCount,
    publishedCount,
    draftCount,
    defaultCount
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 复制操作 */
const copyRef = ref()
const openCopy = (id: number) => {
  copyRef.value.open(id)
}

/** 模板配置操作 */
const templateConfigRef = ref()
const openTemplateConfig = (id: number) => {
  templateConfigRef.value.open(id)
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalSchemeVO) => {
  switch (command) {
    case 'publish':
      await handlePublish(row.id!)
      break
    case 'disable':
      await handleDisable(row.id!)
      break
    case 'setDefault':
      await handleSetDefault(row.id!)
      break
    case 'copy':
      openCopy(row.id!)
      break
    case 'template':
      openTemplateConfig(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 发布方案 */
const handlePublish = async (id: number) => {
  try {
    await publishScheme(id)
    message.success('发布成功')
    await getList()
  } catch {}
}

/** 停用方案 */
const handleDisable = async (id: number) => {
  try {
    await message.confirm('确认停用该方案？')
    await disableScheme(id)
    message.success('停用成功')
    await getList()
  } catch {}
}

/** 设为默认 */
const handleSetDefault = async (id: number) => {
  try {
    await setDefaultScheme(id)
    message.success('设置成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteScheme(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportScheme(queryParams)
    download.excel(data, '评价方案.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取方案状态标签类型 */
const getSchemeStatusTagType = (status: number) => {
  const typeMap = { 0: 'warning', 1: 'success', 2: 'danger' }
  return typeMap[status] || ''
}

/** 获取方案状态文本 */
const getSchemeStatusText = (status: number) => {
  const textMap = { 0: '草稿', 1: '已发布', 2: '已停用' }
  return textMap[status] || '未知'
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
